﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.ServiceLocation;
using Peak.Core;
using Peak.Web.Controllers.Models;
using Peak.Web.Controllers.Services;
using SharpArch.Core.PersistenceSupport;
using SharpArch.Web.ModelBinder;
using Peak.Core.DataInterfaces;

namespace Peak.Web.Controllers.Binders
{
  public class ProjectBinder : DefaultModelBinder
  {
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      IProjectRepository projectRepository = ServiceLocator.Current.GetInstance<IProjectRepository>();
      HttpCookie httpCookie = controllerContext.HttpContext.Request.Cookies[SessionService.CurrentProjectId];
      if(httpCookie == null)
      {
        throw new ProjectNotSelectedException();
      }
      
      bindingContext.ModelMetadata.Model = projectRepository.Get(Convert.ToInt32(httpCookie.Value));            
      return base.BindModel(controllerContext, bindingContext);
    }
  }
}